Rust: Module System
WIP
This doc is compatible with Rust2018(1.31) or later.
TL;DR
extern crate is now optional.
path
crate means root module.
self means current module.
super means parent module.
use brings paths into a scope.
(use imports macro)
example
code: directory structure
├── Cargo.lock
├── Cargo.toml
├── src
│ ├── main.rs
│ ├── module_a.rs
│ ├── module_b.rs
│ ├── module_c
│ │ └── submodule.rs
│ └── module_c.rs
code: Cargo.toml
name = "test"
version = "0.1.0"
actix-web = "0.7.18" # for example
code: main.rs
// declare all modules.
mod module_a;
mod module_b;
mod module_c;
// use keyword without extern crate is now available.
use actix_web::{server, App, Query, http, Json, Result};
fn main() {
module_a::a();
module_b::b();
module_c::submodule::sub();
println!("Hello, world!");
}
code: module_a.rs
// crate keyword means the root module.
use crate::module_b;
pub fn a() {
}
fn private_a() {
module_b::b();
}
code: module b.rs
// super keyword means the parent module.
use super::module_a;
pub fn b() {
}
fn private_b() {
module_a::a();
}
code: module_c.rs
// declare submodule by module_c directory as public.
pub mod submodule;
// declare submodule in the same file.
mod submodule_inflie {
pub fn c() {
}
}
pub fn c() {
}
fn private_c() {
submodule_inflie::c();
}
code: submodule.rs
pub fn sub() {
}
references